//
//  ViewController.m
//  客户端Socket
//
//  Created by 叶文凯 on 16/12/6.
//  Copyright © 2016年 葱花思鸡蛋. All rights reserved.
//

#import "ViewController.h"
#import "GCDAsyncSocket.h"
@interface ViewController ()<UITextFieldDelegate,GCDAsyncSocketDelegate>
@property(nonatomic,strong)GCDAsyncSocket * clientSocket;
@property (weak, nonatomic) IBOutlet UITextField *inputTextField;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.inputTextField.delegate = self;
}
// 当点击键盘回车的时候调用 向服务器发送消息
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSString *content = textField.text;
    [self.clientSocket writeData:[content dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
    
    return  YES;
}
#pragma mark - 连接到客户端
// 当客户端连接到服务器时调用
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
    NSLog(@"可以准备接收消息");
    [sock readDataWithTimeout:-1 tag:0];
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    // 一直保持接收服务器发送的数据
    [sock readDataWithTimeout:-1 tag:0];
    
}


// 连接到服务器
- (IBAction)connectSever:(id)sender {
    
  BOOL isSuccess = [self.clientSocket connectToHost:@"127.0.0.1" onPort:1234 error:nil];
    if (isSuccess) {
        NSLog(@"连接到服务器成功");
    }else
    {
        NSLog(@"连接服务器失败");
    }
}


// 懒加载客户端的socket
- (GCDAsyncSocket *)clientSocket
{
    if (_clientSocket == nil) {
        _clientSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue() socketQueue:nil];
    }
    return _clientSocket;
}



@end
